package com.bawei.mvvm.http

import androidx.lifecycle.LiveData
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class LiveDataCallAdapterFactory: CallAdapter.Factory() {
    override fun get(
        returnType: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit
    ): CallAdapter<*, *>? {
        //returnType：LiveData<ApiResponse<MutableList<GoodsType>>>
        //判断类型是否为LiveData
       if(getRawType(returnType) != LiveData::class.java){
           return null
       }
        //获得里面的第一个泛型ApiResponse
       var observerType = getParameterUpperBound(0, returnType as ParameterizedType)
       // 第一个泛型ApiResponse的具体类型
       var rawType =  getRawType(observerType)
        if(rawType != ApiResponse::class.java){
            throw IllegalArgumentException("type must be ApiResponse")
        }
        if(!ParameterizedType::class.java.isInstance(observerType)){
            throw IllegalArgumentException("resource must be Parameterized")
        }

        return LiveDataCallAdapter<Any>(observerType)


    }
}